// upload.js
layui.use(['upload', 'element', 'layer'], function(){
    var $ = layui.jquery
        ,upload = layui.upload
        ,element = layui.element
        ,layer = layui.layer;

    // 封装上传功能
    function setupImageUpload(buttonId, previewImageId, statusTextId, progressBarFilter) {
        var token = sessionStorage.getItem('token');
        var baseUrl = 'http://localhost:8888/api/admin';

        var uploadInst = upload.render({
            elem: '#' + buttonId,
            url: baseUrl + '/file/fileUpload',
            headers: {
                'Authorization': token
            },
            accept: 'images', //允许上传的文件类型
            before: function (obj) {
                obj.preview(function (index, file, result) {
                    $('#' + previewImageId).attr('src', result); //图片链接（base64）
                });

                element.progress(progressBarFilter, '0%'); //进度条复位
                layer.msg('上传中', { icon: 16, time: 0 });
            },
            done: function (res) {
                // 如果上传失败
                if (res.code > 0) {
                    return layer.msg('上传失败');
                }
                // 上传成功的一些操作
                $('#' + statusTextId).html(''); //置空上传失败的状态
            },
            error: function () {
                // 演示失败状态，并实现重传
                var demoText = $('#' + statusTextId);
                demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
                demoText.find('.demo-reload').on('click', function () {
                    uploadInst.upload();
                });
            },
            // 进度条
            progress: function (n, elem, e) {
                element.progress(progressBarFilter, n + '%'); // 可配合 layui 进度条元素使用
                if (n === 100) {
                    layer.msg('上传完毕', { icon: 1 });
                }
            }
        });
    }

    // 将函数暴露到全局
    window.setupImageUpload = setupImageUpload;
});
